1 /** 2 The following examples come from 3 $(LINK http://zetcode.com/databases/mysqltutorial/constraints/). 4 */ 5 module test.examples_set_constraint; 6 7 version(D_Ddoc) 8 { 9 /// 10 class BlankClassSoDocsWillBeGenerated { } 11 } 12 13 14 /** 15 This example is for the SET constraints. The table 16 in SQL can be created by 17 $(D $(D $(D sql 18 CREATE TABLE Students 19 ( 20 Id INTEGER NOT NULL PRIMARY KEY, 21 Name VARCHAR(55), 22 Certificates SET('A1', 'A2', 'B1', 'C1') 23 ); 24 25 ))) 26 */ 27 unittest 28 { 29 import db_constraints; 30 31 class Student 32 { 33 private int _Id; 34 @PrimaryKeyColumn @NotNull 35 @property int Id() 36 { 37 return _Id; 38 } 39 @property void Id(int value) 40 { 41 setter(_Id, value); 42 } 43 private string _Name; 44 @property string Name() 45 { 46 return _Name; 47 } 48 @property void Name(string value) 49 { 50 setter(_Name, value); 51 } 52 private string _Certificates; 53 // Certificates can only have values that 54 // are among the set below. 55 @SetConstraint!("A1", "A2", "B1", "C1") 56 @property string Certificates() 57 { 58 return _Certificates; 59 } 60 @property void Certificates(string value) 61 { 62 setter(_Certificates, value); 63 } 64 this(int Id_, string Name_, string Certificates_) 65 { 66 this._Id = Id_; 67 this._Name = Name_; 68 this._Certificates = Certificates_; 69 initializeKeyedItem(); 70 } 71 72 mixin KeyedItem!(); 73 } 74 75 // A1 and B1 are both allowed in the set so no error is raise here 76 auto paul = new Student(1, "Paul", "A1,B1"); 77 // we can see paul's certificates are the same as they came in 78 assert(paul.Certificates == "A1,B1"); 79 80 // all of jane's certificates are acceptable but not in order 81 auto jane = new Student(2, "Jane", "A1,B1,A2"); 82 // the set constraint sorts the certificates for you 83 assert(jane.Certificates == "A1,A2,B1"); 84 85 // now lets try with some duplicates 86 jane.Certificates = "A1,A2,B1,A1"; 87 // the set constraint will also remove duplicates 88 assert(jane.Certificates == "A1,A2,B1"); 89 90 // if we enter in certificates that are not allowed we should expect an exception 91 import std.exception : assertThrown; 92 assertThrown!CheckConstraintException(new Student(3, "Mark", "A1,A2,D1,D2")); 93 }